//
//  KKImagePickerManager.m
//  KKImagePickerController
//
//  Created by Mac mini on 16/1/20.
//  Copyright © 2016年 JuniorCodingPerson. All rights reserved.
//

#import "KKImageGroupsViewController.h"
#import "KKImagePickerModel.h"
#import "KKImagePickerManager+Tools.h"

#import "UIImage+Helper.h"

//#import "RootNavigationController.h"
#import "KKNavigationController.h"

#pragma mark - KKImagePickerManager methods

@interface KKImagePickerManager() <UIActionSheetDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate> {
    
    UIViewController __weak *_kk_rootViewController;
    
    KKNavigationController *_kk_navigationController;
    
    UIImagePickerController *_kk_imagePickerController;
}

@end

@implementation KKImagePickerManager

+ (instancetype)kk_defaultManager {
    
    static KKImagePickerManager *pickerManager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        pickerManager = [KKImagePickerManager new];
    });
    return pickerManager;
}

- (void)setMaxLimit:(NSInteger)maxLimit {
    
    KKImagePickerSet *pickerSet = [KKImagePickerSet pickerSet];
    pickerSet.kk_maxLimit = maxLimit;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        
        _kk_rootViewController = [[[UIApplication sharedApplication] keyWindow] rootViewController];
        
//        if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]) {
//            _kk_imagePickerController = [UIImagePickerController new];
//            _kk_imagePickerController.delegate = self;
//            _kk_imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
//        }
        
        KKImageGroupsViewController *groupTableViewController = [KKImageGroupsViewController new];
        _kk_navigationController = [[KKNavigationController alloc] initWithRootViewController: groupTableViewController];
        
        UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithBarButtonSystemItem: UIBarButtonSystemItemCancel target: self action: @selector(kk_dismiss)];
        //item.tintColor = [UIColor colorWithRed:0.000 green:0.606 blue:1.000 alpha:1.000];
//        item.tintColor = [UIColor whiteColor];
        groupTableViewController.navigationItem.title = @"相册";
        groupTableViewController.navigationItem.rightBarButtonItem = item;
        
        [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(kk_save) name: KKImagePickerDismissNotificationName object: nil];
    }
    return self;
}

- (void)dealloc {
    
    [[NSNotificationCenter defaultCenter] removeObserver: self];
}

#pragma mark - UIImagePickerControllerDelegate methods

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    
    [picker dismissViewControllerAnimated: true completion: nil];
    _kk_imagePickerController = nil;
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    
    UIImage* image = info[UIImagePickerControllerOriginalImage];
    if (self.edit) {
        image = info[UIImagePickerControllerEditedImage];
    }
    if (self.resultBlock && image) {
        self.resultBlock(@[image.kk_fixOrientation]);
    }
    
    [picker dismissViewControllerAnimated: true completion: nil];
    _kk_imagePickerController = nil;
}

#pragma mark - Private methods

- (void)kk_save {
    
    NSArray *selectedItems = [[KKImagePickerSet pickerSet] kk_selectedItems];
    NSMutableArray * selectedImages = [NSMutableArray array];
    
    PHImageRequestOptions *options = [[PHImageRequestOptions alloc] init];
    options.synchronous = YES;
    for (KKImageItem* item in selectedItems) {
        PHAsset *asset = item.asset_8;
        [[PHImageManager defaultManager] requestImageForAsset: asset targetSize: CGSizeMake(asset.pixelWidth, asset.pixelHeight) contentMode:PHImageContentModeDefault options:options resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
            [selectedImages addObject: result];
        }];
    }
    
    if (self.resultBlock && selectedImages.count) {
        self.resultBlock(selectedImages);
    }

    
    [self kk_dismiss];
}

- (void)kk_dismiss {
    
    [_kk_navigationController popToRootViewControllerAnimated: false];
    [_kk_navigationController dismissViewControllerAnimated: true completion: nil];
}

- (BOOL)kk_authStatusWithCamera {
    
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType: AVMediaTypeVideo];
    
    switch (authStatus) {
        case AVAuthorizationStatusNotDetermined:
        {
            __weak typeof(self) weakSelf = self;
            [AVCaptureDevice requestAccessForMediaType: AVMediaTypeVideo completionHandler:^(BOOL granted) {
                
                if (granted) {
                    [weakSelf kk_takePictureFromCamera];
                }
            }];
            
            return false;
        }
            break;
        case AVAuthorizationStatusRestricted:
        case AVAuthorizationStatusDenied:
        {
            [KKImagePickerManager kk_showErrorMessage: @"请在设备的\"设置-隐私-相机\"中允许访问相机权限"];
            return false;
        }
            break;
        default:
            break;
    }
    
    return true;
}

- (BOOL)kk_authStatusWithAlbum {
    
    PHAuthorizationStatus authStatus = [PHPhotoLibrary authorizationStatus];
    switch (authStatus) {
        case PHAuthorizationStatusNotDetermined:
        {
            __weak typeof(self) weakSelf = self;
            [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
                
                if (status == PHAuthorizationStatusAuthorized) {
                    [weakSelf kk_takePictureFromAlbum];
                }
            }];
            
            return false;
        }
            break;
        case PHAuthorizationStatusRestricted:
        case PHAuthorizationStatusDenied:
        {
            [KKImagePickerManager kk_showErrorMessage: @"请在设备的\"设置-隐私-照片\"中允许访问相册权限"];
            return false;
        }
            break;
        default:
            break;
    }
    return true;
}

#pragma mark - Public methods
- (void)kk_takePicture {
    
    if (_kk_rootViewController == nil) {
        _kk_rootViewController = [[[UIApplication sharedApplication] keyWindow] rootViewController];
    }
    
    __weak typeof(self) weakSelf = self;
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle: @"选取照片" message: nil preferredStyle: UIAlertControllerStyleActionSheet];
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle: @"取消" style:UIAlertActionStyleCancel handler:nil];
    [alertController addAction: cancelAction];
    
    UIAlertAction *action1 = [UIAlertAction actionWithTitle: @"拍照" style: UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        [weakSelf kk_takePictureFromCamera];
    }];
    [alertController addAction: action1];
    
    UIAlertAction *action2 = [UIAlertAction actionWithTitle: @"相册" style: UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        [weakSelf kk_takePictureFromAlbum];
    }];
    [alertController addAction: action2];
    
    [_kk_rootViewController presentViewController: alertController animated: true completion: nil];
}

- (void)kk_takePictureFromCamera {
    
    if (![self kk_authStatusWithCamera]) {
        return;
    }
    
    if (_kk_rootViewController == nil) {
        _kk_rootViewController = [[[UIApplication sharedApplication] keyWindow] rootViewController];
    }
    
    if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera] && _kk_imagePickerController == nil) {
        _kk_imagePickerController = [UIImagePickerController new];
        _kk_imagePickerController.delegate = self;
    }
    if (_kk_imagePickerController == nil) {
        [KKImagePickerManager kk_showErrorMessage: @"设置暂不支持拍照功能"];
        return;
    }
    _kk_imagePickerController.allowsEditing = self.edit;
    _kk_imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
    
    [_kk_rootViewController presentViewController: _kk_imagePickerController animated: true completion: nil];
}

- (void)kk_takePictureFromAlbum {
    
    if (![self kk_authStatusWithAlbum]) {
        return;
    }
    
    if (_kk_rootViewController == nil) {
        _kk_rootViewController = [[[UIApplication sharedApplication] keyWindow] rootViewController];
    }
    
    if (self.edit) {
        if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypePhotoLibrary] && _kk_imagePickerController == nil) {
            _kk_imagePickerController = [UIImagePickerController new];
            _kk_imagePickerController.delegate = self;
        }
        _kk_imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        _kk_imagePickerController.allowsEditing = self.edit;
        [_kk_rootViewController presentViewController: _kk_imagePickerController animated: true completion: nil];
        return;
    }
    
    
    //  清空原有的数据
    [[KKImagePickerSet pickerSet] kk_cleanAllItems];
    
    [_kk_rootViewController presentViewController: _kk_navigationController animated: true completion: nil];
}

@end
